﻿using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class PlugTangentTools : EditorWindow
{
    public Mesh _targetMesh;

    [MenuItem("Tools/计算描边数据")]
    public static void ShowWindow()
    {
        var window = GetWindow<PlugTangentTools>();
    }

    private void OnGUI()
    {
        _targetMesh = EditorGUILayout.ObjectField("原始模型", _targetMesh, typeof(Mesh), true) as Mesh;

        if (GUILayout.Button("保存"))
        {
            if (_targetMesh == null)
            {
                EditorUtility.DisplayDialog("错误", "模型不能为空", "好");
                return;
            }

            WirteAverageNormalToTangent(_targetMesh);
        }

        EditorGUILayout.LabelField("保存目录为：Assets/OutlineMesh", EditorStyles.wordWrappedLabel);
    }

    private static void WirteAverageNormalToTangent(Mesh mesh)
    {
        var averageNormalHash = new Dictionary<Vector3, Vector3>();
        for (var j = 0; j < mesh.vertexCount; j++)
        {
            if (!averageNormalHash.ContainsKey(mesh.vertices[j]))
            {
                averageNormalHash.Add(mesh.vertices[j], mesh.normals[j]);
            }
            else
            {
                averageNormalHash[mesh.vertices[j]] = (averageNormalHash[mesh.vertices[j]] + mesh.normals[j]).normalized;
            }
        }

        var averageNormals = new Vector3[mesh.vertexCount];
        for (var j = 0; j < mesh.vertexCount; j++)
        {
            averageNormals[j] = averageNormalHash[mesh.vertices[j]];
        }

        // 写入数据
        int TextureSize = 256;
        Texture2D newMaskTex = new Texture2D(TextureSize, TextureSize, TextureFormat.ARGB32, false);

        var tangents = new Vector4[mesh.vertexCount];
        for (var j = 0; j < mesh.vertexCount; j++)
        {
            Vector3 averageNormal = averageNormals[j];
            tangents[j] = new Vector4(averageNormal.x, averageNormal.y, averageNormal.z, 0);
        }

        Mesh instanceMesh = Instantiate(mesh);
        instanceMesh.tangents = tangents;

        var folderPath = Path.Combine("Assets", "OutlineMesh");

        if (!AssetDatabase.IsValidFolder(folderPath))
        {
            AssetDatabase.CreateFolder("Assets", "OutlineMesh");
        }

        AssetDatabase.CreateAsset(instanceMesh, Path.Combine(folderPath, mesh.name + ".asset"));
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
}
